package com.matt.service.impl;

import com.matt.domain.Contract;
import com.matt.domain.ContractHistory;
import com.matt.foundation.utils.DateUtil;
import com.matt.repository.ContractHistoryRepository;
import com.matt.repository.ContractRepository;
import com.matt.service.ContractHistoryService;
import com.matt.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import static com.matt.foundation.constant.OperateConstant.OPERATE_BACK_MONEY;

/**
 * ********************
 * Created by Ron
 * from com.matt
 * on 2018/6/19 0019.
 * ********************
 */
@Service
public class ContractHistoryServiceImpl implements ContractHistoryService {

    @Autowired
    private ContractHistoryRepository contractHistoryRepository;

    @Autowired
    private ContractRepository contractRepository;

    @Autowired
    private ContractService contractService;

    @Transactional
    @Override
    public ContractHistory save(String staffId, String realName, String imgUrl, String content, String contactId, BigDecimal backMoney) {
        Date now = new Date();
        Contract contract = contractRepository.getOne(contactId);

        //修改合同中实际收到的金额
        BigDecimal nowMoney = contract.getPracticalAmount().add(backMoney);
        contract.setPracticalAmount(nowMoney);
        //处理合同状态
        contractService.processContractStatus(contract, now);
        //处理教务系统逻辑
        contractService.beginTeachRoll(contract);
        contractRepository.save(contract);

        ContractHistory contractHistory = new ContractHistory();
        contractHistory.setStaffId(staffId);
        contractHistory.setOperationType(OPERATE_BACK_MONEY);
        contractHistory.setStaffName(realName);
        contractHistory.setStaffHeadImgUrl(imgUrl);
        contractHistory.setCreated(now);
        contractHistory.setContent("在 " + DateUtil.dateToymd(now) + " 添加了回款记录 " + '\n' + " 回款 " + backMoney + " 元,待回款 \"" + contract.getTotalAmount().subtract(contract.getPracticalAmount()) + " \"");
        contractHistory.setClienteleId(contract.getClienteleId());
        contractHistory.setContractId(contactId);
        contractHistory.setContractStatus(contract.getStatus());
        contractHistory.setContractStatusVal(contract.getStatusVal());
        ContractHistory vo = contractHistoryRepository.save(contractHistory);
        return vo;
    }

    @Override
    public List<ContractHistory> findByContractId(String contractId) {
        return contractHistoryRepository.findByContractIdOrderByCreatedDesc(contractId);
    }
}
